package com.shuoyue.ycgk.ui.news;

import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.FileUtil;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.News;
import com.shuoyue.ycgk.entity.NewsType;
import com.shuoyue.ycgk.ui.common.download.DownloadContract;
import com.shuoyue.ycgk.ui.news.contract.NewsContract;
import com.shuoyue.ycgk.utils.NOpenFiles;
import com.shuoyue.ycgk.utils.ShareUtil;
import com.shuoyue.ycgk.views.BottomWebView;
import com.shuoyue.ycgk.views.dialog.file_dialog.FileDialog;
import com.zzhoujay.richtext.RichText;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.util.ScreenUtils;

public class NewsInfoFullWebActivity extends BaseMvpActivity<NewsContract.Presenter> implements NewsContract.View, DownloadContract.View {


    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.content)
    BottomWebView content;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.filebutton)
    TextView filebutton;
    DownloadContract.Presenter downloadPresenter;

    News newsInfo;
    int id;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_news_info_web_full;
    }

    @Override
    protected void initView() {
        pageTitle.setText("详情");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.mipmap.share);
        initWebView(content);
    }

    public void goTop(View view) {
        if (content != null) {
            content.scrollTo(0, 0);
        }
    }

    public void goBottom(View view) {
        if (content != null) {
            content.scrollToBottom();
        }

    }

    FileDialog fileDialog;

    public void showFile(View view) {
        if (newsInfo == null) {
            return;
        }
        if (fileDialog == null) {
            fileDialog = new FileDialog(mContext, newsInfo.getAttachmentList());
            fileDialog.addSelectCall(noticeFile -> {
                File file = new File(FileUtil.getPath(mContext) + "/资讯/", noticeFile.getAttachmentName());
                if (file.exists()) {
                    NOpenFiles.openFile(NewsInfoFullWebActivity.this, file);
                } else {
                    downloadPresenter.downloadFile(noticeFile.getAttachmentUrl(),
                            new File(FileUtil.getPath(mContext) + "/资讯/", noticeFile.getAttachmentName()).getAbsolutePath());
                }
            });
        }
        fileDialog.show();
    }

    @Override
    public void initData() {
        mPresenter = new NewsContract.Presenter();
        mPresenter.attachView(this);
        downloadPresenter = new DownloadContract.Presenter();
        downloadPresenter.attachView(this);
        id = getIntent().getIntExtra("id", 0);
        mPresenter.getNewsInfo(id);
        content.loadUrl(Constant.HOST_INTERFACE + "/api/share/informationApp.html?id=" + id);
//        content.loadUrl("https://www.baidu.com/");

    }


    @Override
    public void setNewsInfo(News newsInfo) {
        this.newsInfo = newsInfo;
        filebutton.setVisibility(newsInfo.getAttachmentList() == null || newsInfo.getAttachmentList().size() == 0
                ? View.GONE : View.VISIBLE);
    }

    public void initWebView(WebView mWebView) {
        //webView 设置属性
        mWebView.clearCache(true);
//        mWebView.addJavascriptInterface(this, "fhy");
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setTextZoom(250);

        webSettings.setUseWideViewPort(true);//关键点
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存
        webSettings.setAppCacheEnabled(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
//        webSettings.setSupportZoom(true);
        //支持屏幕缩放
//        webSettings.setBuiltInZoomControls(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //关闭webView中缓存
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

//设置自适应屏幕，两者合用
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片

        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {

            }

        });
        WebViewClient wvc = new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
                        "if(myimg.width > maxwidth){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width = maxwidth;" +
                        "}" +
                        "}" +
                        "}";
                String width = String.valueOf(ScreenUtils.widthPixels(mContext));
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("用户单击超连接", url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        };
        mWebView.setWebViewClient(wvc);
    }

    @Override
    public void setNewsList(ListWithPage<News> newsList) {

    }

    @Override
    public void setNewsTypeList(List<NewsType> newsTypeList) {

    }

    @Override
    protected void onDestroy() {
        RichText.clear(this);
        super.onDestroy();

    }


    @OnClick({R.id.back, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv_right:
                if (newsInfo != null)
                    ShareUtil.shareUrl(this, ShareUtil.NEWS_URL + id,
                            newsInfo.getTitle(),
                            "",
                            null);
                break;
        }
    }


    @Override
    public void downloadSuc(File file) {
        NOpenFiles.openFile(this, file);
    }

    @Override
    public void progress(int progress) {

    }

    @Override
    public void downloadStart() {

    }

    @Override
    public void downloadError(String msg) {

    }


    @Override
    public void onBackPressed() {
        back();
    }

    void back() {
        if (content.canGoBack()) {
            content.goBack();
        } else {
            finish();
        }
    }

}
